package com.attunlcok.unlock.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.attunlcok.common.annotation.Anonymous;
import com.attunlcok.unlock.constant.UnlockStatus;
import com.attunlcok.unlock.domain.AttUnlockRecord;
import com.attunlcok.unlock.service.IAttUnlockOrderService;
import com.attunlcok.unlock.service.IAttUnlockRecordService;

/**
 * DHRU API控制器
 * 实现DHRU接口标准，支持客户端集成
 */
@RestController
@RequestMapping("/api")
public class AttUnlockDhruController {
    
    private static final Logger log = LoggerFactory.getLogger(AttUnlockDhruController.class);
    
    @Autowired
    private IAttUnlockOrderService attUnlockOrderService;
    
    @Autowired
    private IAttUnlockRecordService attUnlockRecordService;
    
    // 认证信息 - 固定值
    private static final String API_USERNAME = "admin";
    private static final String API_KEY = "attunlock2024";
    
    /**
     * DHRU API统一入口
     * 支持的操作:
     * - balance: 查询余额
     * - accountinfo: 查询账户信息
     * - imeiservicelist: 获取服务列表
     * - placeimeiorder: 提交IMEI解锁订单
     * - getimeiorder: 查询IMEI解锁订单状态
     */
    @Anonymous
    @PostMapping("/index.php")
    public Map<String, Object> handleDhruRequest(
            @RequestParam("username") String username,
            @RequestParam("apiaccesskey") String apiKey,
            @RequestParam("action") String action,
            @RequestParam(value = "parameters", required = false) String parameters) {
        
        log.info("DHRU API请求: action={}, username={}", action, username);
        
        // 验证用户名和API密钥
        if (!API_USERNAME.equals(username) || !API_KEY.equals(apiKey)) {
            return createErrorResponse("Invalid username or API key");
        }
        
        // 解析parameters参数
        Map<String, String> paramMap = parseParameters(parameters);
        
        // 根据action处理不同的请求
        switch (action) {
            case "balance":
                return getBalance();
            case "accountinfo":
                return getAccountInfo();
            case "imeiservicelist":
                return getServiceList();
            case "placeimeiorder":
                return placeImeiOrder(paramMap);
            case "getimeiorder":
                return getImeiOrder(paramMap);
            default:
                return createErrorResponse("Invalid action: " + action);
        }
    }
    
    /**
     * 获取账户余额
     */
    private Map<String, Object> getBalance() {
        // 构建成功响应
        Map<String, Object> balanceResult = new HashMap<>();
        balanceResult.put("balance", 1000); // 模拟余额
        balanceResult.put("currency", "USD");
        
        List<Map<String, Object>> successList = new ArrayList<>();
        successList.add(balanceResult);
        
        Map<String, Object> response = new HashMap<>();
        response.put("SUCCESS", successList);
        
        return response;
    }
    
    /**
     * 获取账户信息
     */
    private Map<String, Object> getAccountInfo() {
        // 构建账户信息
        Map<String, Object> accountInfo = new HashMap<>();
        accountInfo.put("username", API_USERNAME);
        accountInfo.put("credit", "1000");
        accountInfo.put("currency", "USD");
        accountInfo.put("mail", "admin@attunlock.com");
        
        Map<String, Object> accountResult = new HashMap<>();
        accountResult.put("AccountInfo", accountInfo);
        
        List<Map<String, Object>> successList = new ArrayList<>();
        successList.add(accountResult);
        
        Map<String, Object> response = new HashMap<>();
        response.put("SUCCESS", successList);
        
        return response;
    }
    
    /**
     * 获取服务列表
     */
    private Map<String, Object> getServiceList() {
        // 构建服务列表
        Map<String, Object> serviceList = new HashMap<>();
        
        // 创建服务分类：ATT解锁
        Map<String, Object> attCategory = new HashMap<>();
        attCategory.put("GROUPNAME", "ATT_UNLOCK");
        
        // 添加服务
        Map<String, Object> services = new HashMap<>();
        
        // 服务：ATT通用解锁服务
        Map<String, Object> service = new HashMap<>();
        service.put("SERVICEID", "1");
        service.put("SERVICENAME", "ATT Network Unlock Service");
        service.put("TIME", "1-24 hours");
        service.put("CREDIT", "5.00");
        service.put("INFO", "AT&T网络解锁服务，支持所有型号iPhone、Samsung、LG等设备");
        services.put("1", service);
        
        attCategory.put("SERVICES", services);
        serviceList.put("ATT_UNLOCK", attCategory);
        
        // 构建成功响应
        Map<String, Object> listResult = new HashMap<>();
        listResult.put("LIST", serviceList);
        
        List<Map<String, Object>> successList = new ArrayList<>();
        successList.add(listResult);
        
        Map<String, Object> response = new HashMap<>();
        response.put("SUCCESS", successList);
        
        return response;
    }
    
    /**
     * 提交IMEI解锁订单
     */
    private Map<String, Object> placeImeiOrder(Map<String, String> params) {
        try {
            // 获取IMEI号码
            String imei = params.get("imei");
            if (imei == null || imei.isEmpty()) {
                return createErrorResponse("IMEI number is required");
            }
            
            // 获取服务ID（如果不存在则默认为1）
            String serviceIdStr = params.get("id");
            int serviceId = 1; // 默认服务ID
            if (serviceIdStr != null && !serviceIdStr.isEmpty()) {
                try {
                    serviceId = Integer.parseInt(serviceIdStr);
                } catch (NumberFormatException e) {
                    log.warn("Invalid service ID format: {}, using default service ID 1", serviceIdStr);
                }
            }
            
            log.info("收到DHRU解锁请求，IMEI: {}, 服务ID: {}", imei, serviceId);
            
            // 创建解锁记录
            String orderId = attUnlockOrderService.createAttUnlockOrder(imei);
            
            log.info("DHRU解锁订单创建成功，订单号: {}, 服务ID: {}", orderId, serviceId);
            
            // 构建成功响应
            Map<String, Object> successResult = new HashMap<>();
            successResult.put("REFERENCEID", orderId);
            successResult.put("MESSAGE", "Order placed successfully");
            
            List<Map<String, Object>> successList = new ArrayList<>();
            successList.add(successResult);
            
            Map<String, Object> response = new HashMap<>();
            response.put("SUCCESS", successList);
            
            return response;
        } catch (Exception e) {
            log.error("提交IMEI解锁订单失败", e);
            return createErrorResponse("Failed to place order: " + e.getMessage());
        }
    }
    
    /**
     * 查询IMEI解锁订单状态
     */
    private Map<String, Object> getImeiOrder(Map<String, String> params) {
        try {
            // 获取订单ID
            String orderId = params.get("id");
            if (orderId == null || orderId.isEmpty()) {
                return createErrorResponse("Order ID is required");
            }
            
            log.info("查询DHRU订单状态，订单号: {}", orderId);
            
            // 查询解锁记录
            AttUnlockRecord record = attUnlockOrderService.selectUnlockRecordByOrderId(orderId);
            if (record == null) {
                return createErrorResponse("Order not found");
            }
            
            // 映射状态
            int status = mapStatusToDhru(record.getUnlockStatus());
            
            // 构建成功响应
            Map<String, Object> successResult = new HashMap<>();
            successResult.put("STATUS", status);
            successResult.put("IMEI", record.getImei());
            
            // 如果有请求编号，添加到响应中
            if (record.getRequestNumber() != null && !record.getRequestNumber().isEmpty()) {
                successResult.put("REQUESTNUMBER", record.getRequestNumber());
            }
            
            // 如果解锁成功或失败，添加结果信息
            if (UnlockStatus.SUCCESS.equals(record.getUnlockStatus())) {
                successResult.put("CODE", "解锁成功");
                successResult.put("COMMENTS", "IMEI已成功解锁");
            } else if (UnlockStatus.FAILED.equals(record.getUnlockStatus())) {
                successResult.put("CODE", record.getErrorMsg() != null ? record.getErrorMsg() : "解锁失败");
                successResult.put("COMMENTS", "解锁处理失败");
            } else {
                successResult.put("CODE", "处理中");
                successResult.put("COMMENTS", "订单正在处理中");
            }
            
            List<Map<String, Object>> successList = new ArrayList<>();
            successList.add(successResult);
            
            Map<String, Object> response = new HashMap<>();
            response.put("SUCCESS", successList);
            
            return response;
        } catch (Exception e) {
            log.error("查询IMEI解锁订单状态失败", e);
            return createErrorResponse("Failed to get order: " + e.getMessage());
        }
    }
    
    /**
     * 创建错误响应
     */
    private Map<String, Object> createErrorResponse(String message) {
        Map<String, Object> errorResult = new HashMap<>();
        errorResult.put("MESSAGE", message);
        
        List<Map<String, Object>> errorList = new ArrayList<>();
        errorList.add(errorResult);
        
        Map<String, Object> response = new HashMap<>();
        response.put("ERROR", errorList);
        
        return response;
    }
    
    /**
     * 解析XML参数字符串
     * 简化版本，实际应该使用XML解析库
     */
    private Map<String, String> parseParameters(String parameters) {
        Map<String, String> params = new HashMap<>();
        if (parameters == null || parameters.isEmpty()) {
            return params;
        }
        
        try {
            // 简单的XML解析（仅适用于示例）
            // 实际应使用DOM或SAX解析
            parameters = parameters.replaceAll("<PARAMETERS>|</PARAMETERS>", "");
            String[] tags = parameters.split("</");
            
            for (String tag : tags) {
                if (tag.isEmpty()) continue;
                
                String[] parts = tag.split(">");
                if (parts.length == 2) {
                    String key = parts[0].replaceAll("<", "").toLowerCase();
                    String value = parts[1];
                    params.put(key, value);
                }
            }
        } catch (Exception e) {
            log.error("解析参数失败", e);
        }
        
        return params;
    }
    
    /**
     * 将系统状态码映射为DHRU状态码
     */
    private int mapStatusToDhru(String status) {
        return UnlockStatus.toDhruStatus(status);
    }
} 